import React, { useState } from 'react';
import BreadCrumb from '@/components/BreadCrumb';
import { GetQueryString } from '@/common/constant';
import { useLocation, useHistory } from 'react-router-dom';
import { Loading, Tabs, Table } from '@knownsec/react-component';
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer';
import EmptyData from '@/components/EmptyData';
import { getGroupResult } from '~/API';
import CopyText from '@/components/CopyBoard';
const { TabPane } = Tabs;
import cn from 'classnames';

import s from './style.module.css';

export default function changeDetail() {
  const search = useLocation().search;
  const id = GetQueryString(search, 'id');
  const tid = GetQueryString(search, 'tid');
  const type = GetQueryString(search, 'type');
  const sid = GetQueryString(search, 'sid');
  const rowSid = GetQueryString(search, 'rowSid');
  const backparam = GetQueryString(search, 'back');
  const [loading, setLoading] = useState(false);
  const [diffT, setDiffT] = useState({ t1: '', t2: '' });
  const [diffT2, setDiffT2] = useState({ t1: '', t2: '' });
  const [resource, setResource] = useState([]);

  const [locData, setLocData] = React.useState();
  let breadArr = [
    { link: '/', name: '监测列表' },
    {
      link: {
        pathname: '/dashboard',
        search: `id=${tid}&filter=${encodeURI(backparam)}`,
      },
      name: '结果详情',
    },
    { link: '', name: '篡改详情', active: true },
  ];
  if (sid && sid !== 'undefined' && sid !== 'null') {
    breadArr = [
      { link: '/', name: '监测列表' },
      {
        link: {
          pathname: '/dashboard',
          search: `id=${tid}&sid=${sid}&type=${type}&filter=${encodeURI(backparam)}`,
        },
        name: '结果详情',
      },
      { link: '', name: '篡改详情', active: true },
    ];
  }
  const columnsT = [
    { key: 'name', dataIndex: 'name', className: 'w100', title: '属性' },
    { key: 'change0', dataIndex: 'change0', title: '变更前' },
    { key: 'change1', dataIndex: 'change1', title: '变更后' },
  ];
  const columnsT2 = [
    {
      key: 'url',
      dataIndex: 'url',
      title: '资源地址',
      render: (e) => {
        return <CopyText maxWidth={'340px'} text={e} />;
      },
    },
    {
      key: 'change0',
      dataIndex: 'change0',
      title: '变更前',
      render: (e) => {
        return (
          <div>
            {e.map((item) => {
              return <p>{item}</p>;
            })}
          </div>
        );
      },
    },
    {
      key: 'change1',
      dataIndex: 'change1',
      title: '变更后',
      render: (e) => {
        return (
          <div>
            {e.map((item) => {
              return <p>{item}</p>;
            })}
          </div>
        );
      },
    },
    {
      key: 'state',
      dataIndex: 'state',
      title: '状态',
      className: 'w100',
    },
  ];
  const getDate = async () => {
    const res = await getGroupResult({ id: rowSid, data: { event_id: id } });
    if (res.status === 'success') {
      const data = res.data.data?.events[0]?.detail;
      setLocData(data);
      if (data.text_result?.change?.current) {
        const change = data.text_result.change;
        setDiffT({
          t1: change.baseline.content,
          md51: change.baseline.md5,
          size1: change.baseline.size + 'KB',
          code1: change.baseline.status_code,
          t2: change.current.content,
          md52: change.current.md5,
          size2: change.current.size + 'KB',
          code2: change.current.status_code,
        });
      }
      if (data.structure_result?.change?.current) {
        const change = data.structure_result.change;
        setDiffT2({
          t1: change.baseline.content,
          md51: change.baseline.md5,
          size1: change.baseline.size + 'KB',
          code1: change.baseline.status_code,
          t2: change.current.content,
          md52: change.current.md5,
          size2: change.current.size + 'KB',
          code2: change.current.status_code,
        });
      }
      if (data.resource_result?.changes.length) {
        const arr = data.resource_result?.changes.map((item) => {
          let state = '';
          if (item.baseline?.md5 && item.current?.md5) {
            state = '变化';
          } else if (item.baseline?.md5 && !item.current?.md5) {
            state = '删除';
          } else if (!item.baseline?.md5 && !item.current?.md5) {
            state = '新增';
          }
          const size0 = item.baseline?.size ? item.baseline?.size + 'KB' : '- -';
          const size1 = item.current?.size ? item.current?.size + 'KB' : '- -';
          return {
            url: item.url,
            change0: [
              `md5: ${item.baseline?.md5 || '- -'}`,
              `文件大小: ${size0}`,
              `状态码: ${item.baseline?.status_code || '- -'}`,
            ],
            change1: [
              `md5: ${item.current?.md5 || '- -'}`,
              `文件大小: ${size1}`,
              `状态码: ${item.current?.status_code || '- -'}`,
            ],
            state,
          };
        });
        setResource(arr);
      }
    }
  };
  const changeColor = () => {
    setTimeout(() => {
      const diff = document.querySelectorAll('pre');
      diff.forEach((e) => {
        for (let i = 0; i < e.childNodes.length; i++) {
          const node = e.childNodes[i];
          if (node.className) {
            if (node.className.includes('removed')) {
              node.style.background = '#acf2bd';
            } else if (node.className.includes('added')) {
              node.style.background = '#fdb8c0';
            }
          }
        }
      });
    }, 500);
  };
  // React.useEffect(() => {
    // changeColor();
  // }, [diffT, diffT2]);
  React.useEffect(() => {
    getDate();
  }, []);
  return (
    <>
      <BreadCrumb arr={breadArr} />
      <div className={s.securityinfo}>
        <Loading show={loading} />
        <div className={s.title}>篡改详情</div>
        <div className={s.itemwrap}>
          <div className={s.subtitle}>风险地址</div>
          <div className={cn(s.item, s.redstyle)}>
            <p>{locData?.url ? locData.url : '- -'}</p>
          </div>
        </div>
        <div className={s.tabsBox}>
          {/* <Tabs onChange={changeColor}> */}
          <Tabs>
            <TabPane
              tab={
                <span className={s.tabTitle}>
                  文本变更({(locData?.text_result.change_ratio * 100).toFixed(2)}%)
                </span>
              }
              key={1}
            >
              <div className={s.paneBox}>
                <div key={1}>
                  {!diffT.t2 && !diffT.t1 ? (
                    <EmptyData type={'img'} className={s.nobor} />
                  ) : (
                    <>
                      <div className={s.diffTitle}>
                        <p>变更前</p>
                        <p>变更后</p>
                      </div>
                      <div className={s.diffBox}>
                        <ReactDiffViewer
                          styles={{
                            line: { 'word-break': ' break-all' },
                          }}
                          oldValue={diffT.t1}
                          newValue={diffT.t2}
                          compareMethod={DiffMethod.WORDS}
                          splitView={true}
                          showDiffOnly={false}
                        />
                      </div>
                      <div className={s.infoBox}>
                        <p className={s.infoTitle}>基本信息对比</p>
                      </div>
                      <Table
                        columns={columnsT}
                        data={[
                          { name: 'MD5', change0: diffT.md51, change1: diffT.md52 },
                          { name: '文件大小', change0: diffT.size1, change1: diffT.size2 },
                          { name: '状态码', change0: diffT.code1, change1: diffT.code2 },
                        ]}
                      ></Table>
                    </>
                  )}
                </div>
              </div>
            </TabPane>
            <TabPane
              tab={
                <span className={s.tabTitle}>
                  结构变更({(locData?.structure_result.change_ratio * 100).toFixed(2)}%)
                </span>
              }
              key={2}
            >
              <div className={s.paneBox}>
                <div key={2}>
                  {!diffT2.t2 && !diffT2.t1 ? (
                    <EmptyData type={'img'} className={s.nobor} />
                  ) : (
                    <>
                      <div className={s.diffTitle}>
                        <p>变更前</p>
                        <p>变更后</p>
                      </div>
                      <div className={s.diffBox}>
                        <ReactDiffViewer
                          styles={{
                            line: { 'word-break': ' break-all' },
                          }}
                          oldValue={diffT2.t1}
                          newValue={diffT2.t2}
                          compareMethod={DiffMethod.WORDS}
                          splitView={true}
                          showDiffOnly={false}
                        />
                      </div>
                      <div className={s.infoBox}>
                        <p className={s.infoTitle}>基本信息对比</p>
                      </div>
                      <Table
                        columns={columnsT}
                        data={[
                          { name: 'MD5', change0: diffT2.md51, change1: diffT2.md52 },
                          { name: '文件大小', change0: diffT2.size1, change1: diffT2.size2 },
                          { name: '状态码', change0: diffT.code1, change1: diffT.code2 },
                        ]}
                      ></Table>
                    </>
                  )}
                </div>
              </div>
            </TabPane>
            <TabPane
              tab={
                <span className={s.tabTitle}>
                  资源变更({(locData?.resource_result.change_ratio * 100).toFixed(2)}%)
                </span>
              }
              key={3}
            >
              <div className={s.paneBox}>
                {resource.length <= 0 ? (
                  <EmptyData type={'img'} className={s.nobor} />
                ) : (
                  <>
                    <p className={s.resourceTitle}>
                      本次检测发现{locData?.resource_result?.current_resource_count || '0'}
                      个资源，其中对比基准有变更资源数
                      {locData?.resource_result?.change_count || '0'}个。
                    </p>
                    <Table columns={columnsT2} data={resource}></Table>
                  </>
                )}
              </div>
            </TabPane>
          </Tabs>
        </div>
      </div>
    </>
  );
}
